<?php
/**
 * Joomla! 1.5 component ArticleCashRewards
 *
 * @version $Id: process.php 2009-05-10 01:47:01 svn $
 * @author Maverick
 * @package models
 * @subpackage ArticleCashRewards
 * @license GNU/GPL
 * Website: http://www.boddunan.com
 *
 * Review and approve the articles and assign points and cash rewards.
 * Users can see their articles and the points/cash rewards assigned in the front-end module.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

if(!class_exists('ContentHelperRoute')) require_once (JPATH_SITE . '/components/com_content/helpers/route.php');  

class ArticleCashRewardsModelProcess extends JModel {

  var $_article = null;
  var $_error = null;

  function store(){
	global $acr_config;
    $db                 =& JFactory::getDBO();
    $user               =& JFactory::getUser();

    $article_id         = JRequest::getVar('article_id', 0,'post','INTEGER');
    $points             = JRequest::getVar('points', 0,'post','INTEGER');
    $cash               = JRequest::getVar('cash', 0,'post','FLOAT');
    $author             = JRequest::getVar('author', 0,'post','INTEGER');
    $remarks            = JRequest::getVar('remarks', '','post','STRING');
    $approval_status    = JRequest::getVar('cstate', 0,'post','INTEGER');

    $cash = ($approval_status == 2) ? 0 : $cash;
    $points_diff = 0;
    
    /** Get the already existing amounts */
    $db =& $this->getDBO();
    $query = 'SELECT acr.cash as cash, acr.points as points FROM'.
        ' ' . TABLE_ACR_CONTENT  . ' acr WHERE acr.article_id='.$article_id;
    $db->setQuery($query);
    $result = $db->loadRow();

    // Let try to balance the already awarded points/cash. Add or remove extra points/cash.
    $cash_diff = $cash - ( isset($result[0]) ? $result[0] : 0 );

    if(strcasecmp($acr_config[CONFIG_POINTS_SYSTEM],POINTS_SYSTEM_ACR) == 0 ||
        strcasecmp($acr_config[CONFIG_POINTS_SYSTEM],POINTS_SYSTEM_AUP) == 0){
        $points_diff = $points - ( isset($result[1]) ? $result[1] : 0 );
        $points_query = $points;
    }else{
        $points_diff = 0;
        $points_query = $points;
    }

    if(strcasecmp($acr_config[CONFIG_POINTS_SYSTEM],POINTS_SYSTEM_AUP) == 0){
        $api_AUP = JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helper.php';
        if ( file_exists($api_AUP)){
            require_once ($api_AUP);
            $aupid = AlphaUserPointsHelper::getAnyUserReferreID( $author );
            if($aupid){
                AlphaUserPointsHelper::newpoints( POINTS_SYSTEM_AUP_PLUGIN, $aupid,
                    '', 'Article: ' . $article_id, $points_diff, true);
            }
        }
    }

    if(strcasecmp($acr_config[CONFIG_POINTS_SYSTEM],POINTS_SYSTEM_JOMSOCIAL && !isset($result[0])) == 0){
        include_once( JPATH_SITE . DS . 'components' . DS . 'com_community' . DS . 'libraries' . DS . 'userpoints.php');
        CuserPoints::assignPoint(POINTS_SYSTEM_JOMSOCIAL_PLUGIN . $points, $author);
    }
    
    $query = 'INSERT INTO ' . TABLE_ACR_CONTENT . '(article_id, points, cash,' .
        ' reviewer, review_date, remarks, status) VALUES (' . $article_id .
        ',' . $points_query . ',' . $cash . ',"' . $user->id . '", NOW(),' .
        $db->quote($remarks) . ',' . $approval_status . ')' .
        ' ON DUPLICATE KEY UPDATE points=' . $points_query . ', cash=' . $cash .
        ' ,remarks=' . $db->quote($remarks) . ' , status=' . $approval_status;
    $db->setQuery($query);
//$this->setError($query);
    if($db->query()){
        if($this->_updateUserEarnings($author, $cash_diff, $points_diff)){
            $email_sub = 'An article ';
            $email_body = '';

            if($approval_status == 1){
                $email_sub .= $acr_config[CONFIG_A_ARTICLE_EMAIL_SUB];
                $email_body = $acr_config[CONFIG_A_ARTICLE_EMAIL_BODY];
            }else{
                $email_sub .= $acr_config[CONFIG_R_ARTICLE_EMAIL_SUB];
                $email_body = $acr_config[CONFIG_R_ARTICLE_EMAIL_BODY];
            }
            $query = 'SELECT email FROM #__users WHERE id=' . $author;
            $db->setQuery($query);
            $email = $db->loadResultArray();

            if( count($email) > 0 ){
                ArticlecashrewardsHelper::sendEmail(
                    '"'.$acr_config[CONFIG_SENDER_EMAIL].'"',
                    '"'.$acr_config[CONFIG_SENDER_NAME].'"',
                    $email,
                    '"'. $email_sub .'"',
                    '"'. $email_body .'"'
                );
            }
        }else{
            return false;
        }
    }else{
        return false;
    }
    return true;
  }
  
  function &getArticle($id){
	  if ($this->_loadArticle($id)){
			
			$user	= & JFactory::getUser();

			// Is the category published?
			if (!$this->_article->cat_pub && $this->_article->catid) {
				JError::raiseError( 404, JText::_("Article category not published") );
			}

			// Is the section published?
			if ($this->_article->sectionid) {
				if ($this->_article->sec_pub === null){
					// probably a new item
					// check the sectionid probably passed in the request
					$db =& $this->getDBO();
					$query = 'SELECT published' .
						' FROM #__sections' .
						' WHERE id = ' . (int) $this->_article->sectionid;
					$db->setQuery( $query );
					$this->_article->sec_pub = $db->loadResult();
				}
				if (!$this->_article->sec_pub){
					JError::raiseError( 404, JText::_("Article section not published") );
				}
			}

			// Do we have access to the category?
			if (($this->_article->cat_access > $user->get('aid', 0)) && $this->_article->catid) {
				JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
			}

			// Do we have access to the section?
			if (($this->_article->sec_access > $user->get('aid', 0)) && $this->_article->sectionid) {
				JError::raiseError( 403, JText::_("ALERTNOTAUTH") );
			}
		}
		else {
			$user =& JFactory::getUser();
			$article =& JTable::getInstance('content');
			$article->state			= 1;
			$article->cat_pub		= null;
			$article->sec_pub		= null;
			$article->cat_access	= null;
			$article->sec_access	= null;
			$article->author		= null;
			$article->created_by	= $user->get('id');
			$article->parameters	= new JParameter( '' );
			$article->text			= '';
			$article->points		= 0;
			$article->cash			= 0;
			$article->remarks		= '';

			$this->_article			= $article;
		}

		return $this->_article;
	}
		
		
	/**
	 * Method to load content article data
	 *
	 * @access	private
	 * @return	boolean	True on success
	 * @since	1.5
	 */
	function _loadArticle($id)
	{
		global $mainframe;

		$query = 'SELECT a.id, a.title, a.introtext, a.fulltext, a.state, a.sectionid, u.username AS author,'.
				' a.created, a.modified, u.usertype, cc.title AS category, s.title AS section,' .
				' CASE WHEN CHAR_LENGTH(a.alias) THEN CONCAT_WS(":", a.id, a.alias) ELSE a.id END as slug,'.
				' CASE WHEN CHAR_LENGTH(cc.alias) THEN CONCAT_WS(":", cc.id, cc.alias) ELSE cc.id END as catslug,'.
				' g.name AS groups, s.published AS sec_pub, cc.published AS cat_pub, s.access AS sec_access,'.
				' cc.access AS cat_access, acr.id as acr_id, acr.points, acr.cash, acr.remarks, a.created_by as created_by'.
				' FROM #__content AS a' .
				' LEFT JOIN #__categories AS cc ON cc.id = a.catid' .
				' LEFT JOIN #__sections AS s ON s.id = cc.section AND s.scope = "content"' .
				' LEFT JOIN #__users AS u ON u.id = a.created_by' .
				' LEFT JOIN #__groups AS g ON a.access = g.id'.
				' LEFT JOIN ' . TABLE_ACR_CONTENT  . ' AS acr ON a.id = acr.article_id'.
				' WHERE a.id='.$id;
		$this->_db->setQuery($query);
		$this->_article = $this->_db->loadObject();
		if ( ! $this->_article ) {
			return false;
		}
		return true;
	}

	/**
	* Changes the state of one or more content pages
	*
	* @param string The name of the category section
	* @param integer A unique category id (passed from an edit form)
	* @param array An array of unique category id numbers
	* @param integer 0 if unpublishing, 1 if publishing
	* @param string The name of the current user
	*/
	function approve( $state, $cid )
	{
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db		= & JFactory::getDBO();
		$user	= & JFactory::getUser();
        
		$state = $state ? 1 : 0;
		
		if (count($cid) != 1) {
			return false;
		}

		// Get some variables for the query
		$uid	= $user->get('id');
        
		$query = 'UPDATE #__content SET state = '. $state . ' WHERE id='.$cid;
//echo $query;
        $db->setQuery($query);
		if (!$db->query()) {
			JError::raiseError( 500, $db->getErrorMsg() );
			return false;
		}

		$cache = & JFactory::getCache('com_content');
		$cache->clean();
		
		return true;
	}
	
	function _updateUserEarnings($author, $cash, $points){
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db		= & JFactory::getDBO();
		if (!isset($author)) {
			return false;
		}
		if(!isset($cash)){
			$cash = '0.00';
		}
		if(!isset($points)){
			$points = '0';
		}

		$query = 'INSERT INTO ' . TABLE_ACR_USERS  . '(id, points, cash, articles_cash) VALUES('.
            $author . ',' . $points . ',' . $cash . ',' . $cash . ') ON DUPLICATE KEY UPDATE'.
            ' points = points + (' . $points . '), cash = cash + (' . $cash .
            '), articles_cash = articles_cash + (' . $cash . ')';
		$db->setQuery($query);
//$this->setError($query);
		if (!$db->query()) {
			JError::raiseError( 500, $db->getErrorMsg() );
			return false;
		}

		return true;
	}

    function setError($msg){
        $this->_error = $msg;
    }
    function getError(){
        return $this->_error;
    }
}
?>